package com.orange.cepmobile.android.listener;



import java.util.List;

import com.orange.cepmobile.android.CEPMobileCommon;
import com.orange.cepmobile.android.ngsi.events.Event;
import com.orange.cepmobile.android.service.Service;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;


public class LocationListener extends Listener implements
    android.location.LocationListener {
	public static final String TAG = CEPMobileCommon.LOCATION_LISTENER_TAG;
  private static LocationManager manager;
  private static List<String> locationProviders;
  private Context context;

  public void onLocationChanged(final Location location) {
    final Service service = Service.getInstance();
    final Event event = new Event();
    event.eventType = CEPMobileCommon.EVENT_TYPE_LOCATION;
    final StringBuilder sb = new StringBuilder();
    sb.append("latitude:");
    sb.append(location.getLatitude());
    sb.append(",longitude:");
    sb.append(location.getLongitude());
    event.params = sb.toString();
    service.acceptIncomingEvent(event);
  }

  public void onProviderDisabled(final String provider) {
    // Do nothing
  }

  public void onProviderEnabled(final String provider) {
    // Do nothing
  }

  public void onStatusChanged(final String provider, final int status,
      final Bundle extras) {
    // Do nothing
  }

  @Override
  protected boolean registerImpl(final Context context) {
    if (!Service.checkPermissions(context, new String[] {
        android.Manifest.permission.ACCESS_COARSE_LOCATION,
        android.Manifest.permission.ACCESS_FINE_LOCATION }))
      return false;
    manager = (LocationManager) context
        .getSystemService(Context.LOCATION_SERVICE);
    locationProviders = manager.getAllProviders();
    for (final String provider : locationProviders) {
      Log.v(TAG, "register location provider : " + provider);
      manager.requestLocationUpdates(provider, CEPMobileCommon.LOCATION_MIN_UPDATE_TIME,
    		  CEPMobileCommon.LOCATION_MIN_UPDATE_DISTANCE, this);
    }
    return true;
  }

  @Override
  protected boolean unregisterImpl(final Context context) {
    if (manager != null) {
      manager.removeUpdates(this);
      return true;
    }
    return false;
  }
}
